import DGDialogLayout from "../../../components/DGDialogLayout/DGDialogLayout.tsx";
import DGDrawerLayout from "../../../components/DGDrawerLayout/DGDrawerLayout.tsx";
import {Box} from "@mui/material";
import {FC, useState} from "react";
import {useNavigate} from "react-router-dom";
import DGConnect from "../../../sources/DGConnect.ts";
import DGTextView from "../../../components/DGTextView.tsx";
import {Util} from "../../../sources/Util.ts";

interface DGRegIndexProps {
    state: boolean,
    switchView: (text: string) => void,
}


const DGRegIndex: FC<DGRegIndexProps> = ({state, switchView}) => {
    // 路由跳转
    const router = useNavigate();
    // 加载状态
    const [loading, setLoading] = useState(false);
    // 错误信息
    const [error, setError] = useState({state: false, text: ""});


    // 关闭函数
    const handleClose = () => {
        // 关闭面板
        switchView("");
        // 后退
        router(-1);
    }

    // 提交函数
    const handleSubmit = () => {
        // 清空错误信息
        setError({state: false, text: ""});
        // 开始加载
        setLoading(true);
        // 发送初始化请求
        DGConnect.POST(JSON.stringify({type: "register", index: 1}), result => {
            // 关闭加载
            setLoading(false);
            // 设置错误信息
            if (result["data"]["code"] !== 200) return setError({
                state: true, text: "初始化失败！点击重试！错误信息：" + result["data"]["message"]
            });
            // 设置 SESSION
            Util.Storage.setSession("linked", result["data"]['result']);
            // 成功跳转
            switchView("reg_email");
        }, error => {
            // 关闭加载
            setLoading(false);
            // 设置错误信息
            setError({state: true, text: "遇到了一些问题，请尝试重试，或者及时联系我们！错误信息：" + error["stack"]});
        });
    }

    // DOM 节点
    const ContentView = (<>
        <DGTextView Body Bold>
            非常感谢您注册逐梦园账户！
            通过注册，您将享受更多丰富的内容和资源，同时还可以保存和同步您的数据，实现多设备无缝访问。
        </DGTextView>
        {error.state && <DGTextView variant="body2" color="error">{error.text}</DGTextView>}
    </>);

    // 返回组件节点
    return (<Box>
        {/* DGDialogLayout 样式 */}
        <DGDialogLayout
            submit={{name: "开始", click: () => handleSubmit()}}
            back={{name: "返回", click: () => switchView("login_index")}}
            title="欢迎注册" state={state} close={() => handleClose()} load={loading} PANEL>
            {ContentView}
        </DGDialogLayout>
        {/*DGDrawerLayout 样式 */}
        <DGDrawerLayout
            submit={{name: "开始", click: () => handleSubmit()}}
            more={{name: "返回", click: () => switchView("login_index")}}
            title="欢迎注册" state={state} close={() => handleClose()} flex="bottom" load={loading} PANEL>
            {ContentView}
        </DGDrawerLayout>
    </Box>);
}
export default DGRegIndex;